//global to know if result is displaying for machine or for drive and folders       
var isLoadedFresh = true;
var localpageparentid=0;
var ajaxrowlistcount = 9;

var postTypeToRead={'feeds':1,'techno':7,'page':5,'blog':6};
var requestType=postTypeToRead.feeds;

//global for parents
var breadCrumbArray = [];
var uniquelastfileid = "0";
var firstrowuserfileid = 0;
var globalSearch="";

function printObject(o, vl) {
    var out = '';
    for (var p in o) {
        out += p + ': ' + o[p] + '\n';
    }
    // console.log(out + "\n" + vl);
}


/* #############################          Datagrid for userfiles Building Done           ################################# */

function getTopFiles(cuid,feedsetting,postTypeFeedsToRead,parentid,searchStr) { //verified
    if(typeof strsearch !== undefined && strsearch!="" ){
        globalSearch=strsearch;
    }
    
    if(isNaN(parentid)){
        parentid=0;
    }
    //alert("localpagepaentid: "+localpagepaentid+" parentid: "+parentid);
    if(localpageparentid!=parentid){
        $("#tweets").html("");
    }
    if(parentid>0){
        localpageparentid=parentid;    
    }
    //window.location.reload();
    getTopUserFiles(cuid,feedsetting,postTypeFeedsToRead,localpageparentid,globalSearch);
}

function searchContent(cuid,feedsetting,isInitial,postTypeFeedsToRead,parentid,strsearch,isSearch) { //verified

    if(typeof strsearch !== undefined && strsearch!="" ){
        globalSearch=strsearch;
    }
    else{
        globalSearch="";
    }
    OnViewMore(cuid,feedsetting,isInitial,postTypeFeedsToRead,parentid,globalSearch);
}

function OnViewMore(cuid,feedsetting,isInitial,postTypeFeedsToRead,parentid,strsearch) { //verified
    var searchTitle="";
    
    if (document.getElementById("filesloading")) {
        if (document.getElementById("filesloading").style.display == '' || document.getElementById("filesloading").style.display == 'block') {
            return false;
        }
    }
    var isViewMoreReq = true;
    if(isNaN(parentid)){
        parentid=0;
    }
    //alert("localpagepaentid: "+localpagepaentid+" parentid: "+parentid);
    if(localpageparentid!=parentid || isInitial==true){
        $("#tweets").html("");        
    }
    if(strsearch!="" && typeof strsearch !== 'undefined'){
        //alert("inside");
        globalSearch=strsearch;
    }
    else{
        globalSearch=strsearch="";
        //alert("clear");
        if(document.getElementById("technoSearch")){
            document.getElementById("technoSearch").value="";
        }
    }
    //alert(strsearch);
    //if(parentid>0){
//        localpageparentid=parentid;    
//    }
    localpageparentid=parentid;
    getmoreUserFiles(isViewMoreReq,isInitial,cuid,feedsetting,postTypeFeedsToRead,localpageparentid,globalSearch);
}

function showNoRecords(){
    if(document.getElementById("nofeedrecord")){
        $('#nofeedrecord').remove();
    }
    if(document.getElementById("feedloading")){
        $('#feedloading').remove();
    }
    
    $('#tweets').append("<div class='feed' id='nofeedrecord'><table width='100%' border='0'><tbody><tr id='norecords' ><td colspan='3' align='center' style='padding-top:40px'><table><tr><td>No Post Found</td></tr></table></td></tr></tbody></table></div>");
}
//supportive function to show loading
function showloadingonfileslist(isviewmorereq) {
    $('#tweets').append("<div class='feed' id='feedloading'><table width='100%' border='0'><tbody><tr id='fileloading' ><td colspan='3' align='center' style='padding-top:40px'><table><tr><td><img id='filesloading' src='images/ajax-loader.gif' alt='ajax-loader'></td><td>Loading....</td></tr></table></td></tr></tbody></table></div>");
}

//supportive function to show loading gif
function showFilesListingLoading(isviewmorereq) {
    showloadingonfileslist(isviewmorereq);
}

//function to get more file records
function getmoreUserFiles(isMore,isInitial,cuid,feedsetting,postTypeFeedsToRead,parentid,searchStr) { //verified
    var hiddenfieldvalue = "";
    var lastuserfileid = 0;

    if (isInitial) { //means page loaded for first time (normal, deleted, searched)
        uniquelastfileid = 0;
        lastuserfileid = 0;
    }
    else {
        if (isMore) {
            lastuserfileid = $('#tweets').find("#lstfileidtd").html();
            if (!isNaN(lastuserfileid)) {
                uniquelastfileid = lastuserfileid;
            }
        }
    }

  getUserFiles(isMore, isInitial,cuid,feedsetting,uniquelastfileid,postTypeFeedsToRead,parentid,searchStr);            
}

function getTopUserFiles(cuid,feedsetting,postTypeFeedsToRead,parentid,searchStr) { //verified
    var hiddenfieldvalue = "";
    var firstUserFileId = 0;
    firstUserFileId = $('#tweets').find(".lstfeedtime").first().val();
    if (!isNaN(firstUserFileId)) {
        uniquefirstfileid = firstUserFileId;
    }

  getUserFilesTop(cuid,feedsetting, firstUserFileId,postTypeFeedsToRead,parentid,true,searchStr)            
}

function isNewFeedsAreThere(cuid,feedsetting,postTypeFeedsToRead,parentid) { //verified
    var hiddenfieldvalue = "";
    var firstUserFileId = 0;
    firstUserFileId = $('#tweets').find(".lstfeedtime").first().val();
        if (!isNaN(firstUserFileId)) {
            uniquefirstfileid = firstUserFileId;
        }
        //alert("calling findnewffeds");
      findNewFeeds(cuid,feedsetting, firstUserFileId,postTypeFeedsToRead,parentid,true);
}


function expireUserActivity(reason){
    if(reason=="session_expired"){
        alert("session expired");
    }
    return false;
}

function hideNewFeedCount(){
    if(document.getElementById("idNewUpdatesCount") && document.getElementById("idNewUpdates")){
        $("#idNewUpdatesCount").html(""); 
        $("#idNewUpdates").css("display","none");
    }
}
function findNewFeeds(cuid,feedsetting, lastfeed,postTypeFeedsToRead,parentid,istopreq){
    var listcount = ajaxrowlistcount;
    if(istopreq==true){
        lastfeed=parseInt(lastfeed);
    }
    var logreq= { uid: cuid, feedsetting: feedsetting,feedid:lastfeed,nFeedsToRead:listcount,postTypeToRead:postTypeFeedsToRead,'parentid':parentid,'iscountreq':1 };
    console.log("request to load data for top req: ");
    console.log(logreq);
    
    $.ajax({
        url: 'ajax/read_newsfeeds.php',
        type: 'post',
        cache: false,
        async: true,
        //dataType: 'json',
        data:logreq

    })
    .done(function(dataRes) {
        //console.log("\n resp: " + dataRes);
        
        var hasRecords=true;
        if (!isNaN(dataRes) && parseInt(dataRes) < 0) {
            return expireUserActivity("session_expired");
        }
        if(dataRes.indexOf("_")==0){
            var dataResCount=dataRes.replace("_","").replace("_","");
            if(!isNaN(dataResCount) && parseInt(dataResCount)>0){
                //alert("response " + dataRes);
                if(document.getElementById("idNewUpdatesCount") && document.getElementById("idNewUpdates")){
                    var postStr=" New Posts";
                    if(parseInt(dataResCount)<=2){
                        postStr=" New Post";
                    }
                    $("#idNewUpdatesCount").html("("+dataResCount+")"+postStr); 
                    $("#idNewUpdates").css("display","");
                }
            }
            else{
                hideNewFeedCount();
            }
        }
    })
    .fail(function(msg) {
    })
    .always(function() {
    });
}
function getUserFilesTop(cuid,feedsetting, lastfeed,postTypeFeedsToRead,parentid,istopreq,searchStr) {
    var listcount = ajaxrowlistcount;
    if(istopreq==true){
        lastfeed=parseInt(lastfeed);
    }
//   console.log("Request for....\n umi: " + umi + "\n did:" + udid + "\n isviewmorereq: " + isviewmorereq + "\n dno: " + dno + "\n expaned item: " + selectedItemElement + "\n search string: " + searchStr + "\n lastuserfileid: " + luserfileid + "\n isInitial: " + isInitial);
    var logreq= { uid: cuid, feedsetting: feedsetting,feedid:lastfeed,nFeedsToRead:listcount,postTypeToRead:postTypeFeedsToRead,'parentid':parentid,sSearch:searchStr };
    console.log("request to load data for top req: ");
    console.log(logreq);
    
    $.ajax({
        url: 'ajax/read_newsfeeds.php',
        type: 'post',
        cache: false,
        async: true,
        //dataType: 'json',
        data:logreq

    })
    .done(function(dataRes) {
        //console.log("\n resp: " + dataRes);
        //alert("rows length: " + dataRes.length);
        var hasRecords=true;
        if (!isNaN(dataRes) && parseInt(dataRes) < 0) {
            return expireUserActivity("session_expired");
        }
        if(dataRes.length > 0 && !isNaN(dataRes)){
            switch(parseInt(dataRes)){
                case 400:
                    hasRecords=false;
                    break;
            }
        }
        if (dataRes.length > 0 && hasRecords==true) {
            
            if(istopreq==true){
                var tempposts=$("#tweets").html();
                tempposts=dataRes+tempposts;
                showFilesListingTop(tempposts);
                var totalrowcount = $("#tweets").find(".feed").length;
                if(parseInt(totalrowcount)>0){
                    totalrowcount=parseInt(totalrowcount)-1;
                    //if(totalrowcount>ajaxrowlistcount){
//                        $("#viewmore").css('display', 'none');
//                    }
                }
                
            }
            

        }
        else {
            //if (hasRecords==false) {
//                showNoRecords();
//            }
//            $("#tweets").find("#fileloading").remove();
//            $("#viewmore").css('display', 'none');
            
        }
    })
    .fail(function(msg) {
    })
    .always(function() {
        //showNoRecords();

    });
}
//function to fill datagrid for userfiles
//getUserFiles(false,true,feedfor,feedsetting,lastfeed); norecords
function getUserFiles(isviewmorereq,isInitial,cuid,feedsetting, lastfeed,postTypeFeedsToRead,parentid,searchStr) {
    var listcount = ajaxrowlistcount;  
    //show Animation for loading files before ajax calling viewmore
    showFilesListingLoading(isviewmorereq);
    if(!isInitial){
        lastfeed=-1*lastfeed;   
    }
    var logreq={ uid: cuid, feedsetting: feedsetting,feedid:lastfeed,nFeedsToRead:listcount,postTypeToRead:postTypeFeedsToRead,'parentid':parentid,sSearch:searchStr };
    console.log("request to load data for view more: ");
    console.log(logreq);
//   console.log("Request for....\n umi: " + umi + "\n did:" + udid + "\n isviewmorereq: " + isviewmorereq + "\n dno: " + dno + "\n expaned item: " + selectedItemElement + "\n search string: " + searchStr + "\n lastuserfileid: " + luserfileid + "\n isInitial: " + isInitial);
    $.ajax({
        url: 'ajax/read_newsfeeds.php',
        type: 'post',
        cache: false,
        async: true,
        //dataType: 'json',
        data: logreq

    })
    .done(function(dataRes) {
        //console.log("\n resp: " + dataRes);
        //alert("rows length: " + dataRes.length);
        var hasRecords=true;
        if (!isNaN(dataRes) && parseInt(dataRes) < 0) {
            return expireUserActivity("session_expired");
        }
        if(dataRes.length > 0 && !isNaN(dataRes)){
            switch(parseInt(dataRes)){
                case 400:
                    hasRecords=false;
                    break;
            }
        }
        if (dataRes.length > 0 && hasRecords==true) {
            //viewmore
            //check if we already have lastfileid then remove that one
            if (document.getElementById('lstfileidrow')) {
                $("#tweets").find('#lstfileidrow').remove();
            }

            var totalrowcount = $("<div>"+dataRes+"</div>").find(".feed").length;

            var trackisneedviewmore = $("<div>"+dataRes+"</div>").find("#rFinds").html();
            //alert("is view more needed: "+parseInt(trackisneedviewmore));
            if (parseInt(trackisneedviewmore) ==1) {
                $("#viewmore").css('display', '');
            }
            else {
                $("#viewmore").css('display', 'none');
            }

            showFilesListing(dataRes, isviewmorereq);

        }
        else {
            if (hasRecords==false) {
                showNoRecords();
            }
            $("#tweets").find("#fileloading").remove();
            $("#viewmore").css('display', 'none');
            
        }
    })
    .fail(function(msg) {
    })
    .always(function() {
        //showNoRecords();

    });
}

//Supportive function for loading listing on datagrid
function waitandLoadListing(dataRes, isviewmorereq) {
    //alert("listing found..");
    if (isviewmorereq) {
        //console.log("\n response found\n\n" + dataRes);
    }
    $("#tweets").slideDown(8000, function() {
        // Animation complete
        $('#tweets').append(dataRes);
    });
    if(document.getElementById("feedloading")){
        $('#feedloading').remove();
    }
}

function waitandLoadListingTop(dataRes) {
    
    $("#tweets").slideDown(8000, function() {
        // Animation complete
        $('#tweets').html(dataRes);
    });
}
//actual file listing helper to handle previous state
function showFilesListing(dataRes, isviewmorereq) {
    if (!isviewmorereq) {
        $("#tweets").find("#fileloading").remove();
    }
    else {
        $("#tweets").find("#fileloading").remove();
    }
    if (dataRes.length > 0) {
        waitandLoadListing(dataRes, isviewmorereq);
    }
}

function showFilesListingTop(dataRes){
    if (dataRes.length > 0) {
        waitandLoadListingTop(dataRes);
    }
}